import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import FlowerListView from '../views/FlowerListView.vue'
import FlowerDetailView from '../views/FlowerDetailView.vue'
import ProfileView from '../views/ProfileView.vue'
import { isUserLoggedIn } from '../services/dataService'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: FlowerListView,
      alias: '/flowers'
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { hideBanner: true }
    },
    {
      path: '/profile',
      name: 'profile',
      component: ProfileView,
      meta: { requiresAuth: true, hideBanner: true }
    },
    {
      path: '/flower/:id',
      name: 'flower-detail',
      component: FlowerDetailView,
      props: true
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue')
    },
  ],
})

/**
 * 应用路由配置：
 * - '/': FlowerListView（与 '/flowers' 别名）
 * - '/login': 登录页（meta.hideBanner 隐藏横幅）
 * - '/profile': 个人主页（meta.requiresAuth 需要登录）
 * - '/flower/:id': 花卉详情页
 * - '/about': 关于
 * 路由守卫：
 * - 拦截 requiresAuth 未登录，重定向到 /login?redirect=目标页
 */
// 简单的登录守卫：需要登录的页面跳转到登录页
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isUserLoggedIn()) {
    next({ path: '/login', query: { redirect: to.fullPath, mode: 'login' } })
  } else {
    next()
  }
})

export default router
